from flask import Blueprint, request, jsonify
import base64
import random
import time

speech_mock_bp = Blueprint('speech_mock', __name__)

@speech_mock_bp.route('/tts', methods=['POST'])
def text_to_speech_mock():
    """模拟文本转语音服务"""
    try:
        data = request.get_json()
        text = data.get('text')
        voice = data.get('voice', 'alloy')
        
        if not text:
            return jsonify({'success': False, 'error': 'Text is required'}), 400
        
        # 模拟生成音频数据（实际应该是真实的音频文件）
        # 这里返回一个假的base64编码数据
        mock_audio_data = base64.b64encode(b"mock_audio_data_for_" + text.encode()).decode('utf-8')
        
        # 模拟处理时间
        time.sleep(0.5)
        
        return jsonify({
            'success': True,
            'data': {
                'audio_data': mock_audio_data,
                'format': 'mp3',
                'text': text,
                'voice': voice
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@speech_mock_bp.route('/asr', methods=['POST'])
def speech_to_text_mock():
    """模拟语音转文本服务"""
    try:
        data = request.get_json()
        audio_data = data.get('audio_data')
        
        if not audio_data:
            return jsonify({'success': False, 'error': 'Audio data is required'}), 400
        
        # 模拟识别结果（实际应该调用真实的ASR服务）
        mock_texts = [
            "Hello world",
            "How are you",
            "Good morning",
            "Thank you",
            "Nice to meet you"
        ]
        
        recognized_text = random.choice(mock_texts)
        confidence = random.uniform(0.85, 0.98)
        
        # 模拟处理时间
        time.sleep(1.0)
        
        return jsonify({
            'success': True,
            'data': {
                'text': recognized_text,
                'confidence': confidence
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@speech_mock_bp.route('/pronunciation-score', methods=['POST'])
def pronunciation_score_mock():
    """模拟发音评分服务"""
    try:
        data = request.get_json()
        reference_text = data.get('reference_text')
        audio_data = data.get('audio_data')
        
        if not all([reference_text, audio_data]):
            return jsonify({'success': False, 'error': 'Reference text and audio data are required'}), 400
        
        # 模拟识别和评分
        # 简单模拟：根据参考文本生成相似的识别结果
        words = reference_text.lower().split()
        recognized_words = []
        
        for word in words:
            # 90%概率正确识别，10%概率有小错误
            if random.random() < 0.9:
                recognized_words.append(word)
            else:
                # 模拟识别错误
                recognized_words.append(word[:-1] if len(word) > 1 else word)
        
        recognized_text = ' '.join(recognized_words)
        
        # 计算模拟分数
        score = calculate_mock_score(reference_text.lower(), recognized_text)
        feedback = generate_mock_feedback(score)
        
        # 模拟处理时间
        time.sleep(1.5)
        
        return jsonify({
            'success': True,
            'data': {
                'overall_score': score,
                'reference_text': reference_text,
                'recognized_text': recognized_text,
                'accuracy': feedback['accuracy'],
                'fluency': feedback['fluency'],
                'pronunciation': feedback['pronunciation'],
                'feedback_text': feedback['text']
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@speech_mock_bp.route('/word-audio/<int:word_id>', methods=['GET'])
def get_word_audio_mock(word_id):
    """模拟获取单词音频"""
    try:
        from src.models.models import Word
        
        word = Word.query.get_or_404(word_id)
        
        # 模拟生成音频数据
        mock_audio_data = base64.b64encode(f"audio_for_{word.en}".encode()).decode('utf-8')
        
        return jsonify({
            'success': True,
            'data': {
                'audio_data': mock_audio_data,
                'format': 'mp3',
                'word': word.en,
                'phonetic': word.phonetic
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

def calculate_mock_score(reference, recognized):
    """计算模拟发音分数"""
    from difflib import SequenceMatcher
    
    similarity = SequenceMatcher(None, reference, recognized).ratio()
    base_score = int(similarity * 100)
    
    # 添加一些随机变化使其更真实
    variation = random.randint(-5, 5)
    score = max(60, min(100, base_score + variation))
    
    return score

def generate_mock_feedback(score):
    """生成模拟发音反馈"""
    if score >= 90:
        return {
            'accuracy': "Excellent",
            'fluency': "Very Good", 
            'pronunciation': "Excellent",
            'text': "Outstanding pronunciation! Keep up the great work!"
        }
    elif score >= 80:
        return {
            'accuracy': "Good",
            'fluency': "Good",
            'pronunciation': "Good", 
            'text': "Good pronunciation! Try to focus on clarity."
        }
    elif score >= 70:
        return {
            'accuracy': "Fair",
            'fluency': "Fair",
            'pronunciation': "Fair",
            'text': "Fair pronunciation. Practice more to improve clarity."
        }
    else:
        return {
            'accuracy': "Needs Improvement",
            'fluency': "Needs Improvement", 
            'pronunciation': "Needs Improvement",
            'text': "Keep practicing! Focus on pronouncing each word clearly."
        }

